import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store/index.js'
Vue.use(VueRouter)
// 动态绑定路由 优化
const home = () => import('../views/home/index.vue')
const article = () => import('../views/article/index.vue')
const question = () => import('../views/Question.vue')
const video = () => import('../views/Video.vue')
const mine = () => import('../views/user/index.vue')
const login = () => import('../views/Login.vue')
const appNav = () => import('../components/appNav.vue')
const chat = () => import('../views/user/chat/index.vue')
const profile = () => import('../views/user/profile/index.vue')

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    name: 'Home',
    components: {
      body: home,
      default: appNav
    }
  },
  {
    path: '/question',
    name: 'Question',
    components: {
      body: question,
      default: appNav
    }
  },
  {
    path: '/video',
    name: 'Video',
    components: {
      body: video,
      default: appNav
    }
  },
  {
    path: '/mine',
    name: 'Mine',
    components:
    {
      body: mine,
      default: appNav
    }
  },
  {
    path: '/login',
    name: 'Login',
    component: login
  },
  {
    path: '/article',
    name: 'Article',
    component: article
  },
  {
    path: '/mine/chat',
    component: chat
  },
  {
    path: '/mine/profile',
    component: profile
  }
]

const router = new VueRouter({
  routes
})

/* 在创建router实例对象之前，手动覆盖原型链的push来吞掉报错catch */
// 先存储默认底层的push
const originPush = VueRouter.prototype.push
// 覆盖原型链的push
VueRouter.prototype.push = function (location, resolve, reject) {
  // this:路由实例对象

  // 判断用户有没有传后面两个可选参数
  if (resolve || reject) {
    return originPush.call(this, location, resolve, reject)
  } else { // 用户只传了第一个参数
    /*
      默认底层： catch()方法代码  throw err : 抛出异常
      吞掉报错原理： 重写catch()方法,把默认底层的 throw err给去掉，就不会抛出异常
      */
    return originPush.call(this, location).catch(() => {

    })
  }
}
// 守卫导航
router.beforeEach((to, from, next) => {
  // console.log(store.state)
  // 如果没有token值并且访问mine页面
  if (!store.state.user.token && to.path === '/mine') {
    next('/login?returnUrl=' + to.fullPath)
  }
  next()
  store.commit('request/cancelToken')
})

export default router
